<template>
  <div class="roles-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">角色管理</h1>
        <p class="page-description">管理系统角色和权限配置</p>
      </div>
      <div class="header-actions">
        <div class="action-group">
          <el-dropdown v-if="canManageRoles" trigger="click" @command="handleSystemAction">
            <el-button>
              <el-icon><Setting /></el-icon>
              <span style="margin: 0 4px;">系统操作</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="init">
                  <el-icon style="margin-right: 8px;"><Refresh /></el-icon>
                  初始化系统角色
                </el-dropdown-item>
                <el-dropdown-item command="sync">
                  <el-icon style="margin-right: 8px;"><RefreshRight /></el-icon>
                  同步系统角色权限
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button 
            @click="handleRefresh"
            :loading="isRefreshing"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button 
            @click="handleCreateRole"
            type="primary"
            v-if="canManageRoles"
          >
            <el-icon><Plus /></el-icon>
            新建角色
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon bg-blue">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ totalRoles }}</div>
          <div class="stat-label">总角色数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon bg-green">
          <el-icon><Setting /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ systemRoles }}</div>
          <div class="stat-label">系统角色</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon bg-orange">
          <el-icon><Setting /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ customRoles }}</div>
          <div class="stat-label">自定义角色</div>
        </div>
      </div>
    </div>

    <!-- Tabs 切换：系统角色 | 项目角色 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="role-tabs">
      <el-tab-pane label="系统角色" name="system">
        <template #label>
          <span class="tab-label">
            <el-icon><Setting /></el-icon>
            <span>系统角色</span>
            <el-badge :value="systemRoleCount" class="tab-badge" />
          </span>
        </template>
      </el-tab-pane>
      <el-tab-pane label="项目角色" name="project">
        <template #label>
          <span class="tab-label">
            <el-icon><User /></el-icon>
            <span>项目角色</span>
            <el-badge :value="projectRoleCount" class="tab-badge" />
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>

    <!-- 搜索和筛选 -->
    <div class="search-filters">
      <div class="search-box">
        <el-icon><Search /></el-icon>
        <input 
          v-model="searchQuery"
          type="text" 
          placeholder="搜索角色名称或代码..."
          class="search-input"
        />
      </div>
      <div class="filters">
        <select v-model="statusFilter" class="filter-select">
          <option value="">全部状态</option>
          <option value="active">启用</option>
          <option value="inactive">禁用</option>
        </select>
        <select v-model="typeFilter" class="filter-select">
          <option value="">全部类型</option>
          <option value="system">系统角色</option>
          <option value="custom">自定义角色</option>
        </select>
      </div>
    </div>

    <!-- 初始加载状态 -->
    <PageLoading 
      v-if="initialLoading"
      :title="isRefreshing ? '正在刷新角色数据' : '正在加载角色数据'"
      :subtitle="isRefreshing ? '请稍候，正在更新数据...' : '请稍候，正在为您准备数据...'"
    />
    
    <!-- 角色列表 -->
    <div v-else class="roles-table-container">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="filteredRoles.length === 0" class="empty-state">
        <div class="empty-icon">
          <el-icon><User /></el-icon>
        </div>
        <h3>暂无角色数据</h3>
        <p>{{ searchQuery ? '没有找到匹配的角色' : '还没有创建任何角色' }}</p>
        <button 
          v-if="!searchQuery && canManageRoles"
          @click="showCreateDialog = true"
          class="btn btn-primary"
        >
          创建第一个角色
        </button>
      </div>

      <table v-else class="roles-table">
        <thead>
          <tr>
            <th>角色名称</th>
            <th>角色代码</th>
            <th>描述</th>
            <th>类型</th>
            <th>状态</th>
            <th>权限数量</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="role in filteredRoles" :key="role.id" class="role-row">
            <td>
              <div class="role-name">
                <div class="role-avatar">
                  {{ role.name.charAt(0) }}
                </div>
                <span>{{ role.name }}</span>
              </div>
            </td>
            <td>
              <code class="role-code">{{ role.code }}</code>
            </td>
            <td>
              <span class="role-description">{{ role.description || '-' }}</span>
            </td>
            <td>
              <span :class="['role-type', role.is_system ? 'system' : 'custom']">
                {{ role.is_system ? '系统角色' : '自定义角色' }}
              </span>
            </td>
            <td>
              <span :class="['status-badge', role.is_active ? 'active' : 'inactive']">
                {{ role.is_active ? '启用' : '禁用' }}
              </span>
            </td>
            <td>
              <span class="permission-count">{{ role.permissions?.length || 0 }}</span>
            </td>
            <td>
              <span class="create-time">{{ formatDate(role.created_at) }}</span>
            </td>
            <td>
              <div class="action-buttons">
                <button 
                  @click="viewRole(role)"
                  class="btn btn-sm btn-outline"
                  title="查看详情"
                >
                  <el-icon><View /></el-icon>
                </button>
                <button 
                  v-if="canManageRoles && !role.is_system"
                  @click="editRole(role)"
                  class="btn btn-sm btn-outline"
                  title="编辑角色"
                >
                  <el-icon><Edit /></el-icon>
                </button>
                <button 
                  v-if="canManageRoles && !role.is_system"
                  @click="deleteRole(role)"
                  class="btn btn-sm btn-danger"
                  title="删除角色"
                >
                  <el-icon><Delete /></el-icon>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 创建/编辑角色对话框 -->
    <div v-if="showCreateDialog || showEditDialog" class="modal-overlay" @click="closeDialogs">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showCreateDialog ? '创建角色' : '编辑角色' }}</h3>
          <button @click="closeDialogs" class="modal-close">
            <el-icon><Close /></el-icon>
          </button>
        </div>
        
        <form @submit.prevent="submitRole" class="role-form">
          <!-- 基本信息卡片 -->
          <div class="form-section">
            <div class="section-header">
              <div class="section-icon">
                <el-icon><InfoFilled /></el-icon>
              </div>
              <div class="section-title">
                <h4>基本信息</h4>
                <p>设置角色的名称、代码和描述信息</p>
              </div>
            </div>
            
            <div class="section-content">
              <div class="form-row">
                <div class="form-group">
                  <label for="roleName">角色名称 <span class="required">*</span></label>
                  <div class="input-wrapper">
                    <el-icon><User /></el-icon>
                    <input 
                      id="roleName"
                      v-model="roleForm.name"
                      type="text" 
                      class="form-input"
                      placeholder="请输入角色名称，如：项目经理"
                      required
                    />
                  </div>
                  <span class="form-hint">角色的显示名称，建议简洁明了</span>
                </div>
                
                <div class="form-group">
                  <label for="roleCode">角色代码 <span class="required">*</span></label>
                  <div class="input-wrapper">
                    <el-icon><Key /></el-icon>
                    <input 
                      id="roleCode"
                      v-model="roleForm.code"
                      type="text" 
                      class="form-input"
                      :placeholder="showCreateDialog ? '将根据角色名称自动生成' : 'project_manager'"
                      pattern="[a-z0-9_]+"
                      required
                      :disabled="showEditDialog"
                      @focus="autoGenerateCode = false"
                    />
                  </div>
                  <span class="form-hint">
                    {{ showCreateDialog ? '将根据角色名称自动生成，可手动修改' : '英文字母、数字和下划线，用于系统识别' }}
                  </span>
                </div>
              </div>
              
              <div class="form-row" v-if="showCreateDialog">
                <div class="form-group">
                  <label for="roleScope">角色作用域 <span class="required">*</span></label>
                  <div class="input-wrapper">
                    <el-icon><Setting /></el-icon>
                    <select 
                      id="roleScope"
                      v-model="roleForm.scope"
                      class="form-input"
                      required
                    >
                      <option value="system">系统角色</option>
                      <option value="project">项目角色</option>
                    </select>
                  </div>
                  <span class="form-hint">系统角色用于全局权限，项目角色用于项目内权限</span>
                </div>
              </div>
              
              <div class="form-group">
                <label for="roleDescription">角色描述</label>
                <div class="input-wrapper">
                  <el-icon><Document /></el-icon>
                  <textarea 
                    id="roleDescription"
                    v-model="roleForm.description"
                    class="form-textarea"
                    placeholder="请描述该角色的职责和权限范围..."
                    rows="3"
                  ></textarea>
                </div>
                <span class="form-hint">详细描述角色的用途和权限范围</span>
              </div>
            </div>
          </div>

          <!-- 权限配置卡片 -->
          <div class="form-section">
            <div class="section-header">
              <div class="section-icon">
                <el-icon><Setting /></el-icon>
              </div>
              <div class="section-title">
                <h4>权限配置</h4>
                <p>选择该角色拥有的系统权限</p>
              </div>
            </div>
            
            <div class="section-content">
              <div class="permissions-header">
                <div class="permissions-stats">
                  已选择 <span class="stats-number">{{ roleForm.permissions.length }}</span> 个权限
                </div>
                <div class="permissions-actions">
                  <button type="button" @click="selectAllPermissions" class="btn-text">
                    全选
                  </button>
                  <button type="button" @click="clearAllPermissions" class="btn-text">
                    清空
                  </button>
                </div>
              </div>
              
              <div class="permissions-grid">
                <div v-for="module in permissionModules" :key="module.code" class="permission-card">
                  <div class="module-header" @click="toggleModule(module.code)">
                    <div class="module-info">
                      <h4 class="module-name">{{ module.name }}</h4>
                      <span class="module-count">{{ module.permissions.length }} 个权限</span>
                    </div>
                    <el-icon class="module-toggle" :class="{ 'is-expanded': expandedModules.includes(module.code) }">
                      <ArrowDown />
                    </el-icon>
                  </div>
                  
                  <div v-show="expandedModules.includes(module.code)" class="module-content">
                    <div class="permission-list">
                      <label 
                        v-for="permission in module.permissions" 
                        :key="permission.code"
                        class="permission-item"
                        :class="{ 'is-selected': roleForm.permissions.includes(permission.code) }"
                      >
                        <input 
                          type="checkbox"
                          :value="permission.code"
                          v-model="roleForm.permissions"
                          class="permission-checkbox"
                        />
                        <div class="permission-info">
                          <span class="permission-name">{{ permission.name }}</span>
                          <span class="permission-code">{{ permission.code }}</span>
                        </div>
                        <span :class="['permission-level', `level-${permission.level}`]">
                          {{ getLevelName(permission.level) }}
                        </span>
                      </label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="form-actions">
            <button type="button" @click="closeDialogs" class="btn btn-outline">
              <el-icon><Close /></el-icon>
              取消
            </button>
            <button type="submit" class="btn btn-primary" :disabled="submitting">
              <el-icon><Check /></el-icon>
              {{ submitting ? '保存中...' : '保存角色' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 查看角色详情对话框 -->
    <div v-if="showViewDialog" class="modal-overlay" @click="showViewDialog = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>角色详情</h3>
          <button @click="showViewDialog = false" class="modal-close">
            <el-icon><Close /></el-icon>
          </button>
        </div>
        
        <div class="role-details" v-if="selectedRole">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <label>角色名称</label>
                <span>{{ selectedRole.name }}</span>
              </div>
              <div class="detail-item">
                <label>角色代码</label>
                <code>{{ selectedRole.code }}</code>
              </div>
              <div class="detail-item">
                <label>角色类型</label>
                <span :class="['role-type', selectedRole.is_system ? 'system' : 'custom']">
                  {{ selectedRole.is_system ? '系统角色' : '自定义角色' }}
                </span>
              </div>
              <div class="detail-item">
                <label>状态</label>
                <span :class="['status-badge', selectedRole.is_active ? 'active' : 'inactive']">
                  {{ selectedRole.is_active ? '启用' : '禁用' }}
                </span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h4>角色描述</h4>
            <p>{{ selectedRole.description || '暂无描述' }}</p>
          </div>
          
          <div class="detail-section">
            <h4>权限列表 ({{ selectedRole.permissions?.length || 0 }})</h4>
            <div class="permissions-list">
              <div v-if="!selectedRole.permissions || selectedRole.permissions.length === 0" class="empty-permissions">
                暂无权限配置
              </div>
              <div v-else class="permission-tags">
                <span 
                  v-for="permission in selectedRole.permissions" 
                  :key="permission"
                  class="permission-tag"
                >
                  {{ getPermissionName(permission) }}
                </span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h4>时间信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <label>创建时间</label>
                <span>{{ formatDate(selectedRole.created_at) }}</span>
              </div>
              <div class="detail-item">
                <label>更新时间</label>
                <span>{{ formatDate(selectedRole.updated_at) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox, type TabPaneName } from 'element-plus'
import { 
  Plus, 
  User, 
  Setting, 
  Search, 
  View, 
  Edit, 
  Delete, 
  Close,
  InfoFilled,
  Key,
  Document,
  ArrowDown,
  Check,
  Refresh,
  RefreshRight
} from '@element-plus/icons-vue'
import { initSystemRoles, syncSystemRolePermissions } from '@/api/roles'
import PageLoading from '@/components/ui/PageLoading.vue'

// 类型定义
interface Role {
  id: string
  name: string
  code: string
  description?: string
  permissions: string[]
  is_system: boolean
  is_active: boolean
  scope?: 'system' | 'project' // 角色作用域
  created_at?: string
  updated_at?: string
}

interface PermissionModule {
  code: string
  name: string
  permissions: Array<{
    code: string
    name: string
    level: string
  }>
}

// 响应式数据
const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const initialLoading = ref(true)
const isRefreshing = ref(false)
const roles = ref<Role[]>([])
const permissionModules = ref<PermissionModule[]>([])

// Tabs 切换
const activeTab = ref<'system' | 'project'>('system')

// 搜索和筛选
const searchQuery = ref('')
const statusFilter = ref('')
const typeFilter = ref('')

// 对话框状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showViewDialog = ref(false)
const selectedRole = ref<Role | null>(null)

// 表单数据
const roleForm = ref({
  name: '',
  code: '',
  description: '',
  scope: 'system' as 'system' | 'project', // 角色作用域
  permissions: [] as string[]
})

// 权限模块展开状态
const expandedModules = ref<string[]>([])

// 是否自动生成代码（只在新建时启用）
const autoGenerateCode = ref(true)

// 角色代码生成映射表
const roleNameMapping: Record<string, string> = {
  '管理员': 'admin',
  '项目经理': 'project_manager',
  '项目管理员': 'project_manager',
  '开发人员': 'developer',
  '开发者': 'developer',
  '程序员': 'developer',
  '测试人员': 'tester',
  '测试员': 'tester',
  '查看者': 'viewer',
  '访客': 'viewer',
  '观察者': 'viewer',
  '产品经理': 'product_manager',
  '产品': 'product_manager',
  '运营专员': 'operations_specialist',
  '运营人员': 'operations_specialist',
  '运营': 'operations_specialist',
  '运维工程师': 'ops_engineer',
  '运维人员': 'ops_engineer',
  '运维': 'ops_engineer',
  '设计师': 'designer',
  'UI设计师': 'ui_designer',
  'UX设计师': 'ux_designer',
  '安全': 'security',
  '安全员': 'security',
}

// 生成角色代码的函数
const generateRoleCode = (roleName: string): string => {
  if (!roleName || !roleName.trim()) {
    return ''
  }
  
  const trimmedName = roleName.trim()
  
  // 检查映射表
  if (roleNameMapping[trimmedName]) {
    return roleNameMapping[trimmedName]
  }
  
  // 处理英文名称
  if (/^[a-zA-Z\s_-]+$/.test(trimmedName)) {
    return trimmedName
      .toLowerCase()
      .replace(/[\s\-_]+/g, '_')
      .replace(/[^a-z0-9_]/g, '')
  }
  
  // 处理中文名称 - 提取关键词
  const wordMap: Record<string, string> = {
    '项目': 'project',
    '管理': 'manager',
    '经理': 'manager',
    '开发': 'developer',
    '测试': 'tester',
    '查看': 'viewer',
    '产品': 'product',
    '设计': 'design',
    '运营': 'operator',
    '运维': 'devops',
    '安全': 'security',
    '人员': '',
    '员': '',
    '者': '',
    '师': '',
  }
  
  const words: string[] = []
  let remaining = trimmedName
  
  for (const [word, eng] of Object.entries(wordMap)) {
    if (remaining.includes(word)) {
      if (eng) {
        words.push(eng)
      }
      remaining = remaining.replace(word, '')
    }
  }
  
  if (words.length > 0) {
    let code = words.join('_')
    // 清理代码
    code = code.replace(/[^a-z0-9_]/g, '')
    if (code && !/^\d/.test(code)) {
      return code
    }
  }
  
  // 如果都匹配不到，返回默认值
  return 'custom_role'
}

// 规范化角色代码
const normalizeRoleCode = (code: string): string => {
  if (!code) return ''
  
  return code
    .toLowerCase()
    .replace(/[\s\-]+/g, '_')
    .replace(/[^a-z0-9_]/g, '')
    .replace(/^(\d)/, 'role_$1')
}

// 监听角色名称变化，自动生成代码（仅在新建时）
watch(() => roleForm.value.name, (newName, oldName) => {
  if (showCreateDialog.value && autoGenerateCode.value) {
    // 如果代码为空或者是自动生成的，则重新生成
    if (!roleForm.value.code || roleForm.value.code === generateRoleCode(oldName || '')) {
      const generatedCode = generateRoleCode(newName)
      if (generatedCode) {
        roleForm.value.code = generatedCode
      }
    }
  }
})

// 监听角色代码输入，规范化代码
watch(() => roleForm.value.code, (newCode) => {
  if (newCode && showCreateDialog.value) {
    // 规范化代码格式
    const normalized = normalizeRoleCode(newCode)
    if (normalized !== newCode) {
      roleForm.value.code = normalized
      return
    }
    
    // 如果用户手动修改了代码，且与自动生成的不同，停止自动生成
    const autoGenerated = generateRoleCode(roleForm.value.name)
    if (autoGenerated && normalized !== autoGenerated) {
      autoGenerateCode.value = false
    }
  }
})

// 计算属性
const canManageRoles = computed(() => {
  // 检查是否有角色管理权限（创建、更新、删除任一权限）
  return userStore.hasPermission('role:create') || 
         userStore.hasPermission('role:update') || 
         userStore.hasPermission('role:delete') ||
         userStore.hasPermission('role:manage')
})

// 根据 scope 筛选角色
const systemRolesList = computed(() => {
  return roles.value.filter(role => role.scope === 'system' || (!role.scope && role.is_system))
})

const projectRolesList = computed(() => {
  return roles.value.filter(role => role.scope === 'project' || (!role.scope && !role.is_system))
})

// 统计信息
const totalRoles = computed(() => roles.value.length)
const systemRoleCount = computed(() => systemRolesList.value.length)
const projectRoleCount = computed(() => projectRolesList.value.length)
const systemRoles = computed(() => systemRolesList.value.filter(role => role.is_system).length)
const customRoles = computed(() => roles.value.filter(role => !role.is_system).length)

// 当前 Tab 的角色列表
const currentScopeRoles = computed(() => {
  return activeTab.value === 'system' ? systemRolesList.value : projectRolesList.value
})

const filteredRoles = computed(() => {
  let filtered = currentScopeRoles.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(role => 
      role.name.toLowerCase().includes(query) ||
      role.code.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(role => 
      statusFilter.value === 'active' ? role.is_active : !role.is_active
    )
  }

  // 类型过滤（系统角色/自定义角色）
  if (typeFilter.value) {
    filtered = filtered.filter(role => 
      typeFilter.value === 'system' ? role.is_system : !role.is_system
    )
  }

  return filtered
})

// Tab 切换处理
const handleTabChange = (_tabName: TabPaneName) => {
  // Tab 切换时重置筛选条件（可选）
  // searchQuery.value = ''
  // statusFilter.value = ''
  // typeFilter.value = ''
}

// 创建角色处理
const handleCreateRole = () => {
  roleForm.value.scope = activeTab.value // 根据当前 Tab 设置默认 scope
  showCreateDialog.value = true
}

// 方法
const loadRoles = async (isRefresh = false) => {
  if (isRefresh) {
    isRefreshing.value = true
    initialLoading.value = true
  }
  try {
    loading.value = true
    const { getRoles } = await import('@/api/roles')
    // 加载所有角色（不传 scope 参数）
    roles.value = await getRoles()
  } catch (error) {
    console.error('Load roles error:', error)
    roles.value = []
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
    if (isRefresh) {
      setTimeout(() => {
        initialLoading.value = false
        isRefreshing.value = false
      }, 300)
    } else if (initialLoading.value) {
      initialLoading.value = false
    }
  }
}

const loadPermissionModules = async () => {
  try {
    // 使用统一的API调用方式
    const { getPermissionModules } = await import('@/api/users')
    const response = await getPermissionModules()
    
    // 处理统一响应格式
    if (response.data && response.data.success) {
      const moduleData = response.data.data
      permissionModules.value = Array.isArray(moduleData) ? moduleData : []
    } else {
      console.error('Load permission modules failed:', response.data?.message)
    }
  } catch (error) {
    console.error('Load permission modules error:', error)
  }
}

const viewRole = (role: Role) => {
  selectedRole.value = role
  showViewDialog.value = true
}

const editRole = (role: Role) => {
  selectedRole.value = role
  roleForm.value = {
    name: role.name,
    code: role.code,
    description: role.description || '',
    scope: role.scope || (role.is_system ? 'system' : 'project'),
    permissions: [...role.permissions]
  }
  showEditDialog.value = true
}

const deleteRole = async (role: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const { deleteRole: deleteRoleAPI } = await import('@/api/roles')
    await deleteRoleAPI(role.id)
    ElMessage.success('角色删除成功')
    await loadRoles()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Delete role error:', error)
      ElMessage.error(error.message || '删除角色失败')
    }
  }
}

const submitRole = async () => {
  try {
    submitting.value = true
    
    const { createRole, updateRole } = await import('@/api/roles')
    
    if (showCreateDialog.value) {
      await createRole(roleForm.value)
      ElMessage.success('角色创建成功')
    } else {
      if (selectedRole.value) {
        await updateRole(selectedRole.value.id, roleForm.value)
        ElMessage.success('角色更新成功')
      }
    }
    
    closeDialogs()
    await loadRoles()
  } catch (error: any) {
    console.error('Submit role error:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

const closeDialogs = () => {
  showCreateDialog.value = false
  showEditDialog.value = false
  selectedRole.value = null
  autoGenerateCode.value = true  // 重置自动生成标志
  roleForm.value = {
    name: '',
    code: '',
    description: '',
    scope: activeTab.value, // 根据当前 Tab 设置默认 scope
    permissions: []
  }
}

const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const getPermissionName = (permissionCode: string) => {
  for (const module of permissionModules.value) {
    const permission = module.permissions.find(p => p.code === permissionCode)
    if (permission) {
      return `${module.name} - ${permission.name}`
    }
  }
  return permissionCode
}

const getLevelName = (level: string) => {
  const levelMap: Record<string, string> = {
    '1': '基础',
    '2': '标准', 
    '3': '高级',
    '4': '管理'
  }
  return levelMap[level] || '未知'
}

const toggleModule = (moduleCode: string) => {
  const index = expandedModules.value.indexOf(moduleCode)
  if (index > -1) {
    expandedModules.value.splice(index, 1)
  } else {
    expandedModules.value.push(moduleCode)
  }
}

const selectAllPermissions = () => {
  const allPermissions: string[] = []
  permissionModules.value.forEach(module => {
    module.permissions.forEach(permission => {
      allPermissions.push(permission.code)
    })
  })
  roleForm.value.permissions = allPermissions
}

const clearAllPermissions = () => {
  roleForm.value.permissions = []
}

// 系统操作处理
const handleSystemAction = async (command: string) => {
  if (command === 'init') {
    await handleInitSystemRoles()
  } else if (command === 'sync') {
    await handleSyncPermissions()
  }
}

// 初始化系统角色
const handleInitSystemRoles = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要初始化系统角色吗？这将创建所有预定义的系统角色，如果角色已存在，会更新其权限列表。',
      '确认初始化',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const result = await initSystemRoles()
    const messages = []
    if (result.created_count > 0) {
      messages.push(`创建了 ${result.created_count} 个系统角色`)
    }
    if (result.updated_count > 0) {
      messages.push(`更新了 ${result.updated_count} 个系统角色的权限`)
    }
    if (result.created_count === 0 && result.updated_count === 0) {
      messages.push('所有系统角色均已存在且权限已同步')
    }
    
    ElMessage.success(messages.join('；'))
    await loadRoles()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Init system roles error:', error)
      ElMessage.error(error.message || '初始化系统角色失败')
    }
  }
}

// 同步系统角色权限
const handleSyncPermissions = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要同步系统角色权限吗？这将更新所有系统角色的权限列表，使其与系统定义保持一致。',
      '确认同步',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const result = await syncSystemRolePermissions()
    const messages = []
    if (result.synced_count > 0) {
      messages.push(`成功同步 ${result.synced_count} 个系统角色的权限`)
    }
    if (result.failed_count > 0) {
      messages.push(`${result.failed_count} 个系统角色同步失败`)
    }
    if (result.synced_count === 0 && result.failed_count === 0) {
      messages.push(`所有 ${result.total_count} 个系统角色的权限已是最新`)
    }
    
    ElMessage.success(messages.join('；'))
    await loadRoles()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Sync permissions error:', error)
      ElMessage.error(error.message || '同步系统角色权限失败')
    }
  }
}

// 刷新角色列表
const handleRefresh = async () => {
  try {
    await Promise.all([
      loadRoles(true),
      loadPermissionModules()
    ])
    ElMessage.success('刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请稍后重试')
  }
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadRoles(),
    loadPermissionModules()
  ])
  initialLoading.value = false
})
</script>

<style scoped>
.roles-management {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: 1px solid transparent;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.btn-primary {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.btn-primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}

.btn-outline {
  background: white;
  color: #374151;
  border-color: #d1d5db;
}

.btn-outline:hover {
  background: #f9fafb;
  border-color: #9ca3af;
}

.action-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.dropdown-icon {
  margin-left: 4px;
  font-size: 12px;
  transition: transform 0.3s;
}

.btn-danger {
  background: #ef4444;
  color: white;
  border-color: #ef4444;
}

.btn-danger:hover {
  background: #dc2626;
  border-color: #dc2626;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-icon.bg-blue { background: #3b82f6; }
.stat-icon.bg-green { background: #10b981; }
.stat-icon.bg-orange { background: #f59e0b; }

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.search-filters {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 24px;
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  flex: 1;
  position: relative;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
}

.search-input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.search-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.filters {
  display: flex;
  gap: 12px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.roles-table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.loading-state, .empty-state {
  padding: 60px 20px;
  text-align: center;
  color: #6b7280;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f4f6;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 48px;
  color: #d1d5db;
  margin-bottom: 16px;
}

.roles-table {
  width: 100%;
  border-collapse: collapse;
}

.roles-table th {
  background: #f9fafb;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
}

.roles-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #f3f4f6;
}

.role-row:hover {
  background: #f9fafb;
}

.role-name {
  display: flex;
  align-items: center;
  gap: 12px;
}

.role-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #3b82f6;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.role-code {
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
}

.role-type {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-type.system {
  background: #dbeafe;
  color: #1d4ed8;
}

.role-type.custom {
  background: #fef3c7;
  color: #d97706;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #dcfce7;
  color: #166534;
}

.status-badge.inactive {
  background: #fee2e2;
  color: #dc2626;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.modal-close {
  background: none;
  border: none;
  font-size: 20px;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
}

.role-form {
  padding: 0;
}

.form-section {
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  margin-bottom: 24px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e2e8f0;
}

.section-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border-radius: 10px;
  margin-right: 16px;
  color: white;
  font-size: 18px;
}

.section-title h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.section-title p {
  margin: 0;
  font-size: 13px;
  color: #64748b;
}

.section-content {
  padding: 24px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.required {
  color: #ef4444;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper .el-icon {
  position: absolute;
  left: 12px;
  color: #9ca3af;
  font-size: 16px;
  z-index: 1;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #ffffff;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
  padding: 12px;
}

.form-hint {
  display: block;
  margin-top: 6px;
  font-size: 12px;
  color: #6b7280;
}

.permissions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.permissions-stats {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.stats-number {
  color: #3b82f6;
  font-weight: 700;
  font-size: 16px;
}

.permissions-actions {
  display: flex;
  gap: 12px;
}

.btn-text {
  background: none;
  border: none;
  color: #3b82f6;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.btn-text:hover {
  background: #eff6ff;
  color: #1d4ed8;
}

.permissions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.permission-card {
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.permission-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #d1d5db;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e2e8f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.module-header:hover {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
}

.module-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.module-count {
  font-size: 12px;
  color: #6b7280;
  background: #e5e7eb;
  padding: 2px 8px;
  border-radius: 12px;
}

.module-toggle {
  font-size: 16px;
  color: #6b7280;
  transition: transform 0.3s ease;
}

.module-toggle.is-expanded {
  transform: rotate(180deg);
}

.module-content {
  background: #ffffff;
}

.permission-list {
  padding: 8px 0;
}

.permission-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
}

.permission-item:hover {
  background: #f8fafc;
  border-left-color: #3b82f6;
}

.permission-item.is-selected {
  background: #eff6ff;
  border-left-color: #3b82f6;
}

.permission-checkbox {
  margin-right: 12px;
  width: 16px;
  height: 16px;
  accent-color: #3b82f6;
}

.permission-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.permission-name {
  font-size: 13px;
  font-weight: 500;
  color: #374151;
}

.permission-code {
  font-size: 11px;
  color: #6b7280;
  font-family: 'Courier New', monospace;
}

.permission-level {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  text-transform: uppercase;
}

.level-1 {
  background: #fef3c7;
  color: #92400e;
}

.level-2 {
  background: #dcfce7;
  color: #166534;
}

.level-3 {
  background: #dbeafe;
  color: #1e40af;
}

.level-4 {
  background: #fce7f3;
  color: #be185d;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

.role-details {
  padding: 24px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item label {
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.detail-item span, .detail-item code {
  font-size: 14px;
  color: #1f2937;
}

.permissions-list {
  margin-top: 12px;
}

.empty-permissions {
  color: #6b7280;
  font-style: italic;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  background: #f3f4f6;
  color: #374151;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>